<template>
  <div class="u-chat">
    <!-- 头部区域 -->
    <header></header>
    <!-- 聊天区域 -->
    <main>
      <el-scrollbar ref="scrollbarRef" @scroll="onScroll($event)">
        <Content :data="config.data" />
      </el-scrollbar>
    </main>
    <!-- 编辑器区域 -->
    <footer>
      <Editor />
    </footer>
  </div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from 'vue'
import Content from './content.vue'
import Editor from './editor.vue'
import { ElScrollbar } from 'element-plus'
import { isEmpty } from 'undraw-ui'

export interface ChatApi {
  id: string | number
  content: string
  uid: string | number
  user: {
    username: string
    avatar: string
  }
  createTime: string
  float?: 'left' | 'right'
}

export interface ConfigApi {
  user: {
    id: string | number
    username: string
    avatar: string
  }
  data: ChatApi[]
}

interface Props {
  config: ConfigApi
}

const props = withDefaults(defineProps<Props>(), {})

const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()

const emit = defineEmits<{
  (e: 'load-more', finish: (val: any[]) => void): void
}>()

let scrollHeight = 0

// watch(props.config.data, (val, oldVal) => {
//   val.forEach(t => {
//     if (props.config.user.id == t.uid) {
//       t.float = 'right'
//     }
//   })
//   console.log(val, oldVal)
//   if (isEmpty(oldVal)) {
//     nextTick(() => {
//       let scrollbar = scrollbarRef.value!
//       scrollbar.setScrollTop(1e16)
//     })
//   }
//   console.log('tst')
//   nextTick(() => {
//     const el = document.getElementById('imChatPanel')
//     console.log(innerRef.value!.scrollHeight)
//     if (el) {
//       // scrollHeight = el.scrollHeight
//     }
//   })
// })

function load(val: any[]) {
  val.forEach(t => {
    if (props.config.user.id == t.uid) {
      t.float = 'right'
    }
  })
  props.config.data!.unshift(...val.reverse())
  nextTick(() => {
    const el = document.querySelector('.u-chat .chat-content')
    const el2 = document.querySelector('.u-chat main')
    if (el && el2) {
      scrollbarRef.value?.setScrollTop(el.scrollHeight - scrollHeight)
      scrollHeight = el.scrollHeight
      if (el2.scrollHeight > el.clientHeight - 10) {
        emit('load-more', load)
      }
    }
  })
  console.log()
}

function onScroll(e: any) {
  if (e.scrollTop == 0) {
    emit('load-more', load)
  }
}

onMounted(() => {
  emit('load-more', load)
})
</script>

<style lang="scss" scoped>
.u-chat {
  background-color: var(--u-bg-color);
  display: flex;
  flex-direction: column;
  height: 100vh;
  header {
    height: 60px;
    border-bottom: 1px solid var(--u-border-color);
  }
  main {
    height: calc(100vh - 60px - 150px);
  }
  footer {
    height: 150px;
  }
}
</style>
